<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Sfexpress 
{

    //private $userid="7550075493";
    //private $userpass="DBC0833D5E081D384230528172E3BDE8";

    
    //private $api_url = 'http://ibse-nginx.sit.sf-express.com:45091/CBTA/ws/sfexpressService?wsdl';
	//private $api_id = '7550075493';
    //private $api_key = 'DBC0833D5E081D384230528172E3BDE8';
    

    private $api_url = 'http://ibse.sf-express.com/CBTA/ws/sfexpressService?wsdl';
	private $api_id = '';
    private $api_key = '';
    
	//private $api_url = 'http://ibse.sf-express.com/CBTA/ws/sfexpressService?wsdl';
	//private $api_id = 'E579007617';
	//private $api_key = 'E9411B7F1675CE5703E31B8197885214';


    public function __construct($param=array()) {
        $this->api_id=$param["apiid"];
        $this->api_key=$param["apikey"];
    }

    public function base64($str){ // base64转码
	
		return base64_encode($str);
		
	}

    public function createsforder($data)
    {

        $xmlArray = array(
            '@attributes' => array(
                'service' => 'OrderService',
                'lang' => 'zh-CN'
            ),
            'Head' => $this->api_id,
            'Body' => array(
                "Order" => array(
                    '@attributes' => array(
                        'j_country'=>'CN',
                        'j_post_code'=>$data["se_postcode"],                        
                        'j_province'=>$data['se_state'],
                        'j_city'=>$data['se_city'],
                        'j_company'=>$data["se_company"],
                        'j_contact'=>$data["sender"],
                        'j_tel'=>$data["se_mobile"],
                        'j_mobile'=>$data["se_mobile"],
                        'j_address'=>$data["se_address"],
                        
                        'd_company'=>'',
                        'd_contact'=>$data['reciver'],
                        'd_tel'=>$data['re_phone'],
                        'd_mobile'=>$data['re_mobile'] ,
                        'd_address'=>$data['re_address'] ,                       
                        'd_province'=>$data['re_state'],
                        'd_city'=>$data['re_city'],
                        'd_country'=>$data['re_country'],
                        'd_post_code'=>$data['re_postcode'],                         
                        'd_email'=>'', 

                        'orderid' => $data["ordersn"],
                        'express_type'=>$data["method"] ,
                        'length'=>$data['length'],
                        'width'=>$data['width'],
                        'height'=>$data['height'],
                        'cargo_total_weight'=>$data['weight']*$data['number'],
                        'operate_flag'=>1,
                        'parcel_quantity'=>1,
                        'returnsign'=>'N', 
                        'is_battery' => 'N'
                    ),
                    'Cargo' =>array(
                        '@attributes' => array(
                                'hscode'=>'',
                                'name'=>$data['cnname'], 
                                'ename'=>$data['enname'], 
                                'unit'=>'PCE', 
                                'amount'=>$data['total'], 
                                'count'=>$data['number'], 
                                'weight'=>$data['weight'],
                    ))
                ))
        );
        //print_r($xmlArray);
        //die();
        $newLog="data:".PHP_EOL.json_encode($xmlArray,JSON_UNESCAPED_UNICODE);
        file_put_contents("sf_".date("Y-m-d").".log", $newLog.PHP_EOL, FILE_APPEND);


        $xml = $this->array2xml($xmlArray,"Request");
        file_put_contents("sf_".date("Y-m-d").".log", $xml.PHP_EOL, FILE_APPEND);


        $result = $this->EncryptionData($xml,$this->api_key);

        file_put_contents("sf_".date("Y-m-d").".log", "result:".PHP_EOL.$result.PHP_EOL, FILE_APPEND);
        //file_put_contents("debug.txt",$result);
        $postObj = json_decode(json_encode(simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        //print_r($postObj);
        //die();
        if (!empty($postObj['Body']['OrderResponse']['@attributes']['mailno'])) {
			$reslut = array(
				'msg' => 'ok',
				'status' => 1,
				'id' => $postObj['Body']['OrderResponse']['@attributes']['mailno'],
				'pdf' => $this->URL($data["ordersn"]),
			);
		}else{
			if (!empty($postObj['ERROR']))
				$reslut = array('status' => 0, 'msg' => '提交数据存在问题!' . chr(10) . $postObj['ERROR']);
			elseif (empty($result))
				$reslut = array('status' => 0, 'msg' => 'API服务器无响应！');
			else
				$reslut = array('status' => 0, 'msg' => '提交数据存在问题!' . $result);
		}

		return $reslut;
    }


    public function URL($ID) {

		$xmlArray = array(
			'@attributes' => array(
				'service' => 'OrderLabelPrintService',
				'lang' => 'zh-CN'
			),
			'Head' => $this->api_id,
			'Body' => array(
				'OrderLabelPrint' => array(
					'@attributes' => array(
						'orderid' => $ID,
						'mailno' => '',
						'dealtype' => '1',
						'pageversion' => 'label',
					)
				)
			)
		);

		$xml = $this->array2xml($xmlArray, 'Request');
		$response = $this->EncryptionData($xml, $this->api_key);

		$postObj = json_decode(json_encode(simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

		if (isset($postObj['Body']['OrderLabelPrintResponse']['@attributes']['pdfUrl']))
			$strURL = $postObj['Body']['OrderLabelPrintResponse']['@attributes']['pdfUrl'];
		else
			$strURL = '';

		return $strURL;
    }
    

	public function _md5($str){ // md5加密并转大写
	
		return strtoupper(md5($str));
		
	}
	
	/**
	 * 加密方法
	 * @param $xml XML字符串
	 * @param $checkword 密钥
	 */
	 
	public function EncryptionData($xml,$checkword){
	
		$md5Data = $this->_md5($xml.$checkword); 
		
		$verifyCode = $this->base64($md5Data);
		
		return $this->callWebServer($xml,$verifyCode); // 调用webserver
	}
	
	/**
	 * 调用webserver
	 * @param $xml XML字符串
	 * @param $verifyCode 加密后的字符串
	 * 返回xml格式
	 */
	 
	public function callWebServer($xml,$verifyCode){ 
	
		$client = new SoapClient($this->api_url);
		
		$result = $client->__soapCall('sfexpressService', array("xml" => $xml, "verifyCode"=> $verifyCode));
		
		return $result; //返回xml格式
    }
    

    private function array2xml($var, $type = 'root', $tag = '') {
        $ret = '';
        if (!is_int($type)) {
            if ($tag)
                return array2xml(array($tag => $var), 0, $type); else {
                $tag .= $type;
                $type = 0;
            }
        }
        $level = $type;
        $indent = str_repeat("\t", $level);
        if (!is_array($var)) {
            $ret .= $indent . '<' . $tag;
            $var = strval($var);
            if ($var == '') {
                $ret .= ' />';
            } else if (!preg_match('/[^0-9a-zA-Z@\._:\/-]/', $var)) {
                $ret .= '>' . $var . '</' . $tag . '>';
            } else {
                $ret .= "><![CDATA[{$var}]]></{$tag}>";
            }
            $ret .= "\n";
        } else if (!(is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) && !empty($var)) {  
            foreach ($var as $tmp)
                $ret .= $this->array2xml($tmp, $level, $tag);
        } else {
            $ret .= $indent . '<' . $tag;
            if ($level == 0)
                $ret .= '';
            if (isset($var['@attributes'])) {
                foreach ($var['@attributes'] as $k => $v) {
                    if (!is_array($v)) {
                        $ret .= sprintf(' %s="%s"', $k, $v);
                    }
                }
                unset($var['@attributes']);
            }
            $ret .= ">\n";
            foreach ($var as $key => $val) {
                $ret .= $this->array2xml($val, $level + 1, $key);
            }
            $ret .= "{$indent}</{$tag}>\n";
        }
        return $ret;
    }

    private function xmlToArray($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }

}